﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

namespace TntOrm.Utility
{
    public class SqlHelper
    {
        private static SqlConnection _Connection;

        public static SqlConnection Connection
        {
            get { return _Connection; }
            set { _Connection = value; }
        }

        public struct ReturnData
        {
            public DataSet ReturnSet;
            public int ReturnValue;
        }

        public enum ExecuteType { Fill, Execute }

        public static ReturnData Execute( SqlCommand Command, ExecuteType Type, bool CloseAfter )
        {
            ReturnData DataToReturn = new ReturnData( );
            
            if( Connection.State == ConnectionState.Closed )
            {
                Connection.Open( );
            }
            
            Command.Connection = Connection;
           
            if( Type == ExecuteType.Fill )
            {
                SqlDataAdapter Addapter = new SqlDataAdapter( );
                Addapter.SelectCommand = Command;

                DataToReturn.ReturnSet = new DataSet( );

                Addapter.Fill( DataToReturn.ReturnSet );
            }
            else if( Type == ExecuteType.Execute )
            {
                SqlDataAdapter Adapter = new SqlDataAdapter( );
                DataToReturn.ReturnValue = Command.ExecuteNonQuery( );
            }

            if( CloseAfter )
            {
                Connection.Close( );
            }

            return DataToReturn;
        }

        public static ReturnData Execute( SqlCommand Command, ExecuteType Type )
        {
            return Execute( Command, Type, false );
        }
    }
}